package com.weirdor.wxchat.facade.base;

import com.alibaba.fastjson.JSONObject;
import com.weirdor.wxchat.facade.vo.AccessToken;
import com.weirdor.wxchat.support.utils.ConfKit;
import com.xiaoleilu.hutool.http.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by weirdor on 2017/11/28.
 *
 * 订阅号
 */
public class AccessTokenAPI {

    private static final Logger logger = LoggerFactory.getLogger(AccessTokenAPI.class);

   //获取access_token的接口地址（GET）
   public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    /**
     * 获取access_token
     *
     * @param appID 唯一id
     *
     * @param secret 管理组的凭证密钥，每个secret代表了对应用、通讯录、接口的不同权限；不同的管理组拥有不同的secret
     * @return
     */
    public static AccessToken getAccessToken(String appID, String secret) {
        AccessToken accessToken = null;
        String requestUrl = access_token_url.replace("APPID", appID).replace("APPSECRET", secret);
        String responce=HttpUtil.get(requestUrl);
        JSONObject jsonObject =JSONObject.parseObject(responce) ;
        // 如果请求成功
        if (null != jsonObject) {
            try {
                accessToken = new AccessToken();
                accessToken.setAccesstoken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getIntValue("expires_in"));
                logger.info("[ACCESSTOKEN]", "获取ACCESSTOKEN成功:{}", new Object[]{accessToken});
            } catch (Exception e) {
                accessToken = null;
                // 获取token失败
                int errcode = jsonObject.getIntValue("errcode");
                String errmsg = jsonObject.getString("errmsg");
                logger.info("[ACCESSTOKEN]", "获取ACCESSTOKEN失败 errcode:{} errmsg:{}", new Object[]{errcode,errmsg});
            }
        }
        return accessToken;
    }

    public static void main(String[] args) {
        try {
            AccessToken s = AccessTokenAPI.getAccessToken(ConfKit.get("AppId"),ConfKit.get("AppSecret"));
            System.out.println(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
